package com.cssy.xxkj.basic.web;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicMaterialsTypeDO;
import com.cssy.xxkj.basic.entity.BasicProductBomDO;
import com.cssy.xxkj.basic.entity.BasicProductBomMaterialsDO;
import com.cssy.xxkj.basic.entity.BasicProductBomProcessDO;
import com.cssy.xxkj.basic.entity.BasicSeriesDO;
import com.cssy.xxkj.basic.service.IBasicMaterialsBomService;
import com.cssy.xxkj.basic.service.IBasicMaterialsTypeService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.service.code.impl.SyCodeService;
@Controller
@RequestMapping("/basic/materbom")
public class MaterialsBomController extends BaseController<BasicProductBomDO>{
	private static final String MANAGER = "/xxkj/basic/bom/MaterialsBomManager";//列表页面
	private static final String EIDT = "/xxkj/basic/bom/MaterialsBomOperation";//添加、修改、显示页面
	
	@Resource(name="basicMaterialsTypeService")
	private IBasicMaterialsTypeService basicmaterTypeService;
	
	@Resource(name="basicMaterialsBomService")
	private IBasicMaterialsBomService basicMaterialsBomService;
	
	@Resource(name = "basicUtilService")
	private IBasicUtilService basicUtilService;
	
	@Resource(name="syCodeService")
	private SyCodeService syCodeService;
	

	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		String ID=request.getParameter("ID");
		List<String> pIdList = new ArrayList<String>();
		pIdList.add(ID);
		if(StringUtils.isNotBlank(ID)){
			SearchConditions pScs = new SearchConditions();
			pScs.addCondition("zd003ParentId", ID, SearchCondition.OP_EQUAL);
			List<BasicMaterialsTypeDO> pTypeList =basicmaterTypeService.findList(pScs);
			if(pTypeList==null){
				pTypeList = new ArrayList<BasicMaterialsTypeDO>();
			}
			for(BasicMaterialsTypeDO pType : pTypeList){
				if(pType==null||StringUtils.isBlank(pType.getId())){
					continue;
				}
				if(!pIdList.contains(pType.getId())){
					pIdList.add(pType.getId());
				}
			}
		}
		scs.addCondition("zd008MaterTypeId",pIdList);
		SearchResult result=	basicMaterialsBomService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}
	
	@RequestMapping(value = "/materList")
	public void materList(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ID=request.getParameter("ID");
		BasicProductBomMaterialsDO  bdo = new BasicProductBomMaterialsDO();
		bdo.setZd001BomId(ID);
		SearchResult result=	basicMaterialsBomService.materList(bdo);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}
	
	@RequestMapping(value = "/processList")
	public void processList(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ID=request.getParameter("ID");
		BasicProductBomProcessDO bdo = new BasicProductBomProcessDO();
		bdo.setZd001BomId(ID);
		SearchResult result = basicMaterialsBomService.processList(bdo);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}

	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			BasicMaterialsTypeDO bd =basicmaterTypeService.findListById(id);
			model.addAttribute("matertype", bd);
			model.addAttribute("flag", "add");
		}else{
			BasicProductBomDO bd =basicMaterialsBomService.findListById(id);
			model.addAttribute("materbom", bd);
			model.addAttribute("flag", "edit");
		}
		//系列
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");//判断是否有删除标识
		List<BasicSeriesDO> series=basicUtilService.resultSeries(scs);
		model.addAttribute("serieslist", series);
		return EIDT;
	}
	
	
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			BasicProductBomDO curAP, BindingResult result, Model model)
	{
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String procssItem = request.getParameter("processItem");
			if(StringUtils.isBlank(procssItem)){
				bodyMap.isFail();
				bodyMap.configWebInfor("工序列表不能为空！");
				return bodyMap.modelMap;
			}
			basicMaterialsBomService.bomSave(request,curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
		

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String isDelete = request.getParameter("isDelete");//标识是否是假删除
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(isDelete==null||"0".equals(isDelete)){
					basicMaterialsBomService.delete(field, SessionUtil.getUser(request));
				}else{
					basicMaterialsBomService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String tr=null;
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);//判断是否有删除标识
		hander.getWheres(scs);
		scs.setLimitPage(false);
		scs.setPageSize(1000);
		List<String> strlist = new ArrayList<String>();
		strlist.add("成品");
		scs.addCondition("zd002Name",strlist);
		List<BasicMaterialsTypeDO> list =basicmaterTypeService.findList(scs);
		if(list.size()>0){
			tr=tree(list);
			AjaxUtil.printJSonArr(response, tr);
		}else{
			AjaxUtil.printJSonArr(response, "");
		}
		
	}
	
	/**
     * 生成tree第一层数据
     **/
	private String  tree(List<BasicMaterialsTypeDO> list) throws SyBaseException {
		StringBuffer sf = new StringBuffer();
		sf.append("[");
		for (int i = 0; i < list.size(); i++) {
			sf.append("{");
			sf.append("\"text\":").append("\"").append(list.get(i).getZd002Name()).append("\"").append(",").append("\"id\":").append("\"").append(list.get(i).getId()).append("\"");
			List<BasicMaterialsTypeDO> list1 =basicmaterTypeService.findParentId(list.get(i).getId());
			if (list1 != null && list1.size() > 0) {
				sf.append(",").append("\"children\":");
				sf.append(tree(list1));
			}
			if (i == (list.size() - 1)) {
				sf.append("}");
			} else {
				sf.append("},");
			}
		}
		sf.append("]");
		return sf.toString();
	}
}
